/**
  ******************************************************************************
  * @file    mg_driver_aes.c
  * @author  
  * @version V1.1
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT 2019 Shanghai Macrogiga Electronics</center></h2>
  *
  ******************************************************************************
  */
#include <string.h>
#include "mg_driver_aes.h"
#include "mg_driver_clock.h"
#include "mg_driver_power.h"

#include <string.h>

void AES_Init(void)
{
    //clock gating if any
    POWER_SetEnableBits(POWER_BIT_AES_EN);
    CLK_SetClockGate(CLK_GATE_AES_EN);
    
//    AES->DATA_SWAP = AES_DIN_SWAP;
    AES->DATA_SWAP = 0;
}

void AES_UnInit(void)
{
    //clock gating if any
    CLK_ClearClockGate(CLK_GATE_AES_EN);
    POWER_SetDisableBits(POWER_BIT_AES_EN);    
}

void AES_Start(void)
{
    AES->START = AES_START;
}

u8 AES_GetDoneFlag(void)
{
    if(AES->ENC_DONE)return 1;
    
    return 0;
}
#if 0
void AES_Enc(u8 *In, u8 *Key, u8 *Out, u8 NewKeyFlag)
{
    u32* InData= (u32*)In;
    u32* OutData= (u32*)Out;
    u32* AesKey= (u32*)Key;
    
    AES->DIN0 = InData[0];
    AES->DIN1 = InData[1];
    AES->DIN2 = InData[2];
    AES->DIN3 = InData[3];
    
    //if(NewKeyFlag)
    {
        AES->KEY0 = AesKey[0];
        AES->KEY1 = AesKey[1];
        AES->KEY2 = AesKey[2];
        AES->KEY3 = AesKey[3];
    }
    
    AES_Start();
    
    while(!AES_GetDoneFlag()); //wait enc done
    
    OutData[0] = AES->DOUT0;
    OutData[1] = AES->DOUT1;
    OutData[2] = AES->DOUT2;
    OutData[3] = AES->DOUT3;    
}

#else
void AES_Enc(u8 *In, u8 *Key, u8 *Out, u8 NewKeyFlag)
{
    u32 InData[4];
    u32* OutData = InData;
    u32 AesKey[4];
    
    //32bit alignment
    memcpy((u8*)InData,In,16);  
    memcpy((u8*)AesKey,Key,16);
    
    AES->DIN0 = InData[0];
    AES->DIN1 = InData[1];
    AES->DIN2 = InData[2];
    AES->DIN3 = InData[3];
    
    //if(NewKeyFlag)
    {
        AES->KEY0 = AesKey[0];
        AES->KEY1 = AesKey[1];
        AES->KEY2 = AesKey[2];
        AES->KEY3 = AesKey[3];
    }
    
    AES_Start();
    
    while(!AES_GetDoneFlag()); //wait enc done
    
    OutData[0] = AES->DOUT0;
    OutData[1] = AES->DOUT1;
    OutData[2] = AES->DOUT2;
    OutData[3] = AES->DOUT3; 

    //32bit alignment
    memcpy(Out,(u8*)OutData,16);
}
#endif
